package initialize

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"jms/global"
	"log"
	"os"
	"time"
)

func InitMysql() {
	fmt.Printf("%s:%s@tcp(%s:%d)", global.ServerConfig.MysqlInfo.DB,
		global.ServerConfig.MysqlInfo.Pass,
		global.ServerConfig.MysqlInfo.Host,
		global.ServerConfig.MysqlInfo.Port)
	fmt.Println("")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		global.ServerConfig.MysqlInfo.User,
		global.ServerConfig.MysqlInfo.Pass,
		global.ServerConfig.MysqlInfo.Host,
		global.ServerConfig.MysqlInfo.Port,
		global.ServerConfig.MysqlInfo.DB,
	)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // Slow SQL threshold
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // Disable color
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		zap.S().Error("failed to connect database", err.Error())
		panic("failed to connect database")
	}
	global.Db = db
	zap.S().Info("数据库连接成功")
}
